﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using YGBookmark.DAL;
using YGBookmark.Models;
using YGBookmark.Utils;

namespace YGBookmark.UI
{
    /// <summary>
    /// 主界面窗体（集成书签管理核心功能）
    /// </summary>
    public partial class MainForm : Form
    {
        #region 控件声明
        private DataGridView dgvBookmarks;
        private TextBox txtSearch;
        private CheckedListBox clbTags;
        private ToolStrip tsMain;
        private StatusStrip ssStatus;
        private SplitContainer scMain;
        private ImageList imgIcons;
        #endregion

        private List<Bookmark> _currentBookmarks = new List<Bookmark>();

        public MainForm()
        {
            InitializeComponent();
            InitializeUI();
            LoadDataAsync();
        }

        #region UI初始化
        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.AutoScaleDimensions = new SizeF(6F, 12F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(1200, 800);
            this.Text = "书签管理系统";
            this.ResumeLayout(false);
        }

        private void InitializeUI()
        {
            // 图像资源
            imgIcons = new ImageList
            {
                ImageSize = new Size(32, 32),
                ColorDepth = ColorDepth.Depth32Bit
            };
            imgIcons.Images.Add("add", Properties.Resources.add.BytesToImage());
            imgIcons.Images.Add("edit", Properties.Resources.edit.BytesToImage());
            imgIcons.Images.Add("delete", Properties.Resources.delete.BytesToImage());
            imgIcons.Images.Add("import", Properties.Resources.import.BytesToImage());
            imgIcons.Images.Add("export", Properties.Resources.export.BytesToImage());
            imgIcons.Images.Add("tagMng", Properties.Resources.edit.BytesToImage());
            
            // 主布局容器
            scMain = new SplitContainer
            {
                Dock = DockStyle.Fill,
                SplitterDistance = 200
            };

            // 左侧面板
            var leftPanel = new Panel { Dock = DockStyle.Fill };
            InitializeLeftPanel(leftPanel);

            // 右侧面板
            var rightPanel = new Panel { Dock = DockStyle.Fill };
            InitializeRightPanel(rightPanel);

            scMain.Panel1.Controls.Add(leftPanel);
            scMain.Panel2.Controls.Add(rightPanel);

            // 工具栏
            tsMain = new ToolStrip { Dock = DockStyle.Top };
            InitializeToolbar();

            // 状态栏
            ssStatus = new StatusStrip { Dock = DockStyle.Bottom };
            ssStatus.Items.Add(new ToolStripStatusLabel { Text = "就绪" });

            this.Controls.AddRange(new Control[] { tsMain, scMain, ssStatus });
        }

        private void InitializeToolbar()
        {
            var btnAdd = CreateToolButton("新增", "add", () => ShowEditForm(new Bookmark("", "")));
            var btnEdit = CreateToolButton("编辑", "edit", EditSelectedBookmark);
            var btnDelete = CreateToolButton("删除", "delete", DeleteSelectedBookmark);
            var btnImport = CreateToolButton("导入", "import", ImportBookmarks);
            var btnExport = CreateToolButton("导出", "export", ExportBookmarks);
            var btnTagMng = CreateToolButton("标签项", "tagMng", TagMng);

            tsMain.Items.AddRange(new ToolStripItem[]
            {
                btnAdd, btnEdit, btnDelete,
                new ToolStripSeparator(),
                btnImport, btnExport,btnTagMng
            });
        }

        private void TagMng()
        {
            using var tagForm = new TagManagerForm();
            if (tagForm.ShowDialog() == DialogResult.OK)
            {
                LoadDataAsync();
            }
        }

        //private ToolStripButton CreateToolButton(string text, string imageKey, Action action)
        //{
        //    return new ToolStripButton(text, imgIcons.Images[imageKey], (s, e) => action())
        //    {
        //        DisplayStyle = ToolStripItemDisplayStyle.ImageAndText,
        //        ImageScaling = ToolStripItemImageScaling.None
        //    };
        //}

        private ToolStripButton CreateToolButton(string text, string imageKey, Action action)
        {
            // 线程安全检查
            if (this.InvokeRequired)
            {
                return (ToolStripButton)this.Invoke(() => CreateToolButton(text, imageKey, action));
            }

            // 资源存在性检查
            if (imgIcons == null)
            {
                throw new InvalidOperationException("ImageList 未初始化");
            }

            if (!imgIcons.Images.ContainsKey(imageKey))
            {
                throw new ArgumentException($"无效的图像键: {imageKey}");
            }

            // 创建按钮
            return new ToolStripButton(text, imgIcons.Images[imageKey], (s, e) => action())
            {
                DisplayStyle = ToolStripItemDisplayStyle.ImageAndText,
                ImageScaling = ToolStripItemImageScaling.None
            };
        }

        private void InitializeLeftPanel(Panel panel)
        {
            var layout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                RowCount = 2,
                RowStyles =
                {
                    new RowStyle(SizeType.Absolute, 40),
                    new RowStyle(SizeType.Percent, 100)
                }
            };

            txtSearch = new TextBox
            {
                Dock = DockStyle.Fill,
                PlaceholderText = "输入关键词搜索...",
                Margin = new Padding(5)
            };
            txtSearch.TextChanged += (s, e) => FilterBookmarks();

            clbTags = new CheckedListBox
            {
                Dock = DockStyle.Fill,
                CheckOnClick = true,
                SelectionMode = SelectionMode.None
            };
            clbTags.ItemCheck += (s, e) => FilterBookmarks();

            layout.Controls.Add(txtSearch, 0, 0);
            layout.Controls.Add(clbTags, 0, 1);
            panel.Controls.Add(layout);
        }

        private void InitializeRightPanel(Panel panel)
        {
            dgvBookmarks = new DataGridView
            {
                Dock = DockStyle.Fill,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                AllowUserToAddRows = false,
                ReadOnly = true
            };
            ConfigureBookmarkColumns();

            var detailsPanel = new Panel { Dock = DockStyle.Bottom, Height = 150 };
            InitializeDetailsPanel(detailsPanel);

            panel.Controls.Add(dgvBookmarks);
            panel.Controls.Add(detailsPanel);
        }

        private void ConfigureBookmarkColumns()
        {
            dgvBookmarks.Columns.AddRange(
                new DataGridViewTextBoxColumn { HeaderText = "标题", DataPropertyName = "Title", FillWeight = 30 },
                new DataGridViewTextBoxColumn { HeaderText = "网址", DataPropertyName = "Url", FillWeight = 40 },
                new DataGridViewTextBoxColumn { HeaderText = "标签", DataPropertyName = "Tags", FillWeight = 20 },
                new DataGridViewTextBoxColumn { HeaderText = "创建时间", DataPropertyName = "CreateTime", FillWeight = 10 }
            );
        }

        private void InitializeDetailsPanel(Panel panel)
        {
            var webBrowser = new WebBrowser { Dock = DockStyle.Fill };
            dgvBookmarks.SelectionChanged += (s, e) =>
            {
                if (dgvBookmarks.CurrentRow?.DataBoundItem is Bookmark bm)
                {
                    webBrowser.Navigate(bm.Url);
                }
            };

            panel.Controls.Add(webBrowser);
        }
        #endregion

        #region 数据操作
        private async void LoadDataAsync()
        {
            try
            {
                var bookmarks = await DatabaseHelper.Instance.ExecuteQueryAsync<Bookmark>(
                    @"SELECT b.*, GROUP_CONCAT(t.Name) AS Tags 
                      FROM Bookmarks b
                      LEFT JOIN BookmarkTags bt ON b.Id = bt.BookmarkId
                      LEFT JOIN Tags t ON bt.TagId = t.Id
                      GROUP BY b.Id");

                var tags = await DatabaseHelper.Instance.ExecuteQueryAsync<Tag>("SELECT * FROM Tags");

                _currentBookmarks = bookmarks;
                dgvBookmarks.DataSource = _currentBookmarks;
                clbTags.Items.Clear();
                foreach (var tag in tags)
                {
                    clbTags.Items.Add(tag.Name, false);
                }
            }
            catch (Exception ex)
            {
                ShowError($"数据加载失败: {ex.Message}");
            }
        }

        private void FilterBookmarks()
        {
            var filtered = _currentBookmarks.AsEnumerable();

            // 关键词过滤
            if (!string.IsNullOrEmpty(txtSearch.Text))
            {
                var keyword = txtSearch.Text.ToLower();
                filtered = filtered.Where(b =>
                    b.Title.ToLower().Contains(keyword) ||
                    b.Summary.ToLower().Contains(keyword));
            }

            // 标签过滤//?
            var selectedTags = clbTags.CheckedItems.Cast<string>();
            if (selectedTags.Any())
            {
                filtered = filtered.Where(b =>
                    selectedTags.All(t => b.Tags.Split(',').Any(bt => bt.Trim() == t)));
            }

            dgvBookmarks.DataSource = filtered.ToList();
        }
        #endregion

        #region 业务逻辑
        private void ShowEditForm(Bookmark bookmark)
        {
            using var editForm = new EditForm(bookmark);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                LoadDataAsync();
            }
        }

        private void EditSelectedBookmark()
        {
            if (dgvBookmarks.CurrentRow?.DataBoundItem is Bookmark bm)
            {
                ShowEditForm(bm);
            }
        }

        private async void DeleteSelectedBookmark()
        {
            if (dgvBookmarks.CurrentRow?.DataBoundItem is Bookmark bm)
            {
                if (MessageBox.Show($"确定删除 '{bm.Title}' 吗？", "确认删除",
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    await DatabaseHelper.Instance.ExecuteNonQueryAsync(
                        "DELETE FROM Bookmarks WHERE Id = @id",
                        new SQLiteParameter("@id", bm.Id));

                    LoadDataAsync();
                }
            }
        }

        private async void ImportBookmarks()
        {
            var dialog = new OpenFileDialog { Filter = "HTML书签|*.html|所有文件|*.*" };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // 实现导入逻辑
                ShowStatus("正在导入书签...");
                await Task.Delay(1000); // 模拟导入操作
                ShowStatus("导入完成");
            }
        }

        private void ExportBookmarks()
        {
            var dialog = new SaveFileDialog { Filter = "CSV文件|*.csv" };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // 实现导出逻辑
                ShowStatus("正在导出书签...");
            }
        }

        private void ShowStatus(string message)
        {
            ssStatus.Items[0].Text = message;
        }

        private void ShowError(string message)
        {
            MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        #endregion

        #region 事件处理
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            DatabaseHelper.Instance.CloseAndFlush();
        }
        #endregion
    }
}